<template>
  <div>
    <Card :bordered="false" dis-hover>
      <Button
        v-hasC="{
          name: 'setting-source-channel-market-add',
          flag: 'v1/setting/source-channel/market-add',
        }"
        type="primary"
        @click="handleAllocation(-1)"
        class="ivu-mb-16"
        >新增</Button
      >
      <Table
        highlight-row
        row-key="id"
        :columns="columns"
        :data="data"
        @on-cell-click="cellclicktable"
      >
        <template slot-scope="{ row }" slot="status">
          <Badge v-if="row.status === '1'" color="green" text="启用" />
          <Badge v-if="row.status === '0'" color="red" text="停用" />
        </template>
        <template slot-scope="{ row }" slot="sort">
          <span v-if="sortshow === row.id">
            <InputNumber
              v-width="'100%'"
              :formatter="$inputday"
              v-model="formItem.sort"
              @on-blur="cellblur"
            ></InputNumber>
          </span>
          <span v-else>{{ row.sort }}</span>
        </template>
        <template slot-scope="{ row }" slot="operation">
          <a
            v-hasC="{
              name: 'setting-source-channel-market-edit',
              flag: 'v1/setting/source-channel/market-edit',
            }"
            @click="handleAllocation(row)"
            >编辑</a
          >
          <Divider
            type="vertical"
            v-hasC="{
              name: 'v1-setting-source-channel-channel-delete',
              flag: 'v1/setting/source-channel/channel-delete',
            }"
          />
          <a
            @click="deleteTag(row)"
            v-hasC="{
              name: 'v1-setting-source-channel-channel-delete',
              flag: 'v1/setting/source-channel/channel-delete',
            }"
            >删除</a
          >
        </template>
      </Table>
      <div class="ivu-mt iuv-text-center">
        <div style="text-align: center;">
          <Page
            show-total
            show-elevator
            show-sizer
            :total="total"
            :current.sync="params.page"
            :page-size="params.pageSize"
            :page-size-opts="pageOpts"
            @on-change="formSize"
            @on-page-size-change="formChangePage"
          />
        </div>
      </div>
    </Card>
    <Modal
      v-model="modal"
      :title="edit ? '编辑' : '新增'"
      :mask-closable="false"
      @on-cancel="handleDrawerCancel('formItem')"
    >
      <Form
        :model="formItem"
        ref="formItem"
        :label-width="80"
        :rules="createRules"
      >
        <FormItem label="名称" prop="input">
          <Input
            v-model="formItem.input"
            placeholder="请输入来源名称,批量新增用逗号分隔"
          />
        </FormItem>
        <FormItem label="父节点">
          <!-- <Cascader
            :data="selectlist"
            trigger="hover"
            clearable
            change-on-select
            v-model="formItem.select"
            :render-format="format"
          ></Cascader> -->
          <TreeSelect
            v-model="formItem.select"
            :data="selectlist"
            placeholder="请选择父节点"
            clearable
            transfer
            @on-change="changetree"
          />
        </FormItem>
        <FormItem label="排序" prop="sort">
          <Input v-model="formItem.sort" type="number" />
        </FormItem>
        <FormItem label="状态">
          <i-switch v-model="formItem.switch">
            <span slot="open">On</span>
            <span slot="close">Off</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleDrawerCancel('formItem')">取消</Button>
        <Button
          type="primary"
          :loading="remarksloading"
          @click="handleSubmit('formItem')"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  settingsourcechannelmarketview,
  settingsourcechannelmarketadd,
  settingsourcechannelmarketedit,
  deleteChannel,
} from "@/api/hqapi";
export default {
  name: "marktingChannel",
  data() {
    return {
      modal: false,
      edit: true,
      selectlist: [],
      remarksloading: false,
      formItem: {
        input: "",
        select: "",
        sort: "",
        switch: true,
      },
      sortshow: undefined,
      createRules: {
        input: [{ required: true, message: "请输入名称", trigger: "blur" }],
        sort: [
          {
            required: false,
            message: "请输入正整数",
            pattern: /^[+]{0,1}(\d+)$/,
            trigger: "blur",
          },
        ],
      }, // 模态框验证规则
      columns: [
        { title: "名称", key: "source_name", tree: true },
        { title: "排序", key: "sort", slot: "sort" },
        { title: "状态", slot: "status" },
        { title: "操作", slot: "operation" },
      ],
      data: [],
      // 请求参数
      params: { page: 1, pageSize: 10 },
      total: 0,
      pageOpts: [10, 15, 20, 30, 50], // 分页每页数量
    };
  },
  mounted() {
    this.initial();
  },
  methods: {
    cellclicktable(row, v) {
      this.logs(v.key);
      this.sortshow = row.id;
      if (v.key === "sort") {
        this.formItem = {
          id: row.id,
          input: row.source_name,
          select: row.pid,
          sort: +row.sort,
          switch: row.status === "1",
        };
      } else {
        this.sortshow = undefined;
      }
      this.logs(this.formItem, this.sortshow);
    },
    cellblur() {
      let config = {
        channel_id: this.formItem.id,
        pid: this.formItem.select,
        status: this.formItem.switch ? 1 : 0,
        sort: this.formItem.sort,
        channel_name: this.formItem.input,
        is_builtin: 0,
      };
      settingsourcechannelmarketedit(config).then(() => {
        this.sortshow = undefined;
        this.formItem = {
          id: "",
          input: "",
          select: "",
          sort: "",
          switch: true,
        };
        this.askData();
      });
    },
    // 初始化
    initial() {
      this.askData();
    },
    deleteTag(row) {
      this.$Modal.confirm({
        title: "删除确认",
        content: "删除后将自动清空患者身上的该渠道,包括子级渠道，不可恢复",
        loading: true,
        onOk: () => {
          deleteChannel({ id: row.id }).then((res) => {
            this.$Modal.remove();
            this.$Message.success("删除成功");
            this.askData();
          });
        },
      });
    },
    // 请求数据
    askData() {
      this.loading = true;
      settingsourcechannelmarketview(this.params).then((res) => {
        this.total = res.total;
        this.data = res.list;
        this.selectlist = res.list;
        this.loading = false;
      });
    },
    /* @函数功能: 分页 */
    formSize(e) {
      this.params.page = e;
      this.askData();
    },
    /* @函数功能: 每页数量 */
    formChangePage(e) {
      this.params.pageSize = e;
      this.askData();
    },
    handleAllocation(row) {
      if (row === -1) {
        this.edit = false;
        this.formItem = {
          id: "",
          input: "",
          select: "",
          sort: "",
          switch: true,
        };
      } else {
        this.edit = true;
        this.formItem = {
          id: row.id,
          input: row.source_name,
          select: row.pid,
          sort: row.sort,
          switch: row.status === "1",
        };
      }
      this.logs(this.formItem.select);
      this.modal = true;
    },
    changetree() {},
    handleDrawerCancel(name) {
      this.$refs[name].resetFields();
      this.modal = false;
      this.formItem = {
        id: "",
        input: "",
        select: "",
        sort: "",
        switch: true,
      };
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let config = {
            channel_id: this.formItem.id,
            pid: this.formItem.select,
            status: this.formItem.switch ? 1 : 0,
            sort: this.formItem.sort,
            channel_name: this.formItem.input,
            is_builtin: 0,
          };

          this.remarksloading = true;
          this.logs(1, config, this.formItem);
          if (this.edit) {
            settingsourcechannelmarketedit(config)
              .then(() => {
                this.$Message.success("编辑成功");
                this.remarksloading = false;
                this.askData();
                this.modal = false;
                this.formItem = {
                  id: "",
                  input: "",
                  select: "",
                  sort: "",
                  switch: true,
                };
              })
              .catch(() => {
                this.remarksloading = false;
              });
          } else {
            settingsourcechannelmarketadd(config)
              .then(() => {
                this.$Message.success("新增成功");
                this.remarksloading = false;
                this.askData();
                this.modal = false;
                this.formItem = {
                  id: "",
                  input: "",
                  select: "",
                  sort: "",
                  switch: true,
                };
              })
              .catch(() => {
                this.remarksloading = false;
              });
          }
        }
      });
    },
  },
};
</script>
<style scoped>
/deep/.ivu-cascader-not-found-tip {
  padding: 5px;
}
</style>
